/**
 *  Copyright (c) 2006, Reliable Source, Inc. 
 *  All Rights Reserved.
 */
package org.reliablesource.prism.ui.popup.actions;

import java.io.IOException;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.reliablesource.prism.core.IPrismElement;
import org.reliablesource.prism.core.IPrismTutorial;
import org.reliablesource.prism.core.plugin.PrismCorePlugin;

/**
 * 
 * SavePrismElementAction.java<br> 
 * Created on: Mar 11, 2006<br>
 *
 * @author Dennis Park 
 * 		<a href="mailto:dennis.park@gmail.com">dennis.park@gmail.com</a>
 *
 *  @since 1.0
 */
public class SavePrismElementAction extends Action{
	
	protected IPrismElement selection;

	public void run() {

		FileDialog dlg = new FileDialog(Display.getDefault().getActiveShell(),
				SWT.SAVE);
		String[] ext = { "xml" };
		dlg.setFilterExtensions(ext);
		final String chosenPath = dlg.open();
		try {
			IPrismTutorial tut = (IPrismTutorial) PrismCorePlugin.getDefault()
					.getModel().getChild(0);
			PrismCorePlugin.getDefault().saveTutorial(tut, chosenPath + ".xml");
		} catch (final IOException _ioe) {
			// final IStatus _status = StatusUtil.newStatus(Status.ERROR, "Save
			// operation failed: Invalid resource type chosen: " + chosenPath +
			// " is not a valid resource.", _ioe);
			// ErrorDialog.openError(null, "Error loading resource",
			// StatusUtil.getCause(_ioe).getLocalizedMessage(), _status);
		}
	}
	
	public boolean setSelection(final ISelection _selection){
		setEnabled(false);
		if (_selection != null) {
			
			IStructuredSelection _strSelection = (IStructuredSelection) _selection;

			if(_strSelection.isEmpty())
				return false;
			
			Object _selectedObj = _strSelection.getFirstElement();
				if (_selectedObj instanceof IPrismElement) {
					selection = (IPrismElement) _selectedObj;
					setEnabled(selection instanceof IPrismTutorial);
				}
		}
		return isEnabled();
	}
		
}
